package com.t11.consumer.service.impl;

import com.t11.common.pojo.LzwOrder;
import com.t11.common.service.OrderService;
import com.t11.consumer.mapper.GoodsMapper;
import com.t11.consumer.mapper.OrderMapper;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl implements OrderService {


    @Resource
    OrderMapper orderMapper;

    @Resource
    GoodsMapper goodsMapper;


    @Transactional
    @KafkaListener(topics = "topic-lzw")
    @Override
    public int createOrder(LzwOrder lzwOrder) {
        try {
            // 模拟消息队列时间延迟
            TimeUnit.SECONDS.sleep(2);
            // 支付成功生成订单
            orderMapper.insert(lzwOrder);
        } catch (Exception e) {
            System.out.println("数据库插入失败！重复插入");
        }
        // 并减少真实库存
        goodsMapper.decrementStock();
        return 1;
    }

    @Override
    public LzwOrder findOrderByUserPhone(String userPhone) {
        return orderMapper.findByUserPhone(userPhone);
    }

    @Override
    public boolean payMoney() {
        // 模拟支付（0-9）
        int flag = (int) (Math.random() * 10);
        // 如果随机数大于三表示支付成功
        return flag > 3;
    }
}
